//
//  KFDMarketInfoContainer.m
//  
//
//  Created by JIRENTIANXIANG on 6/13/15.
//
//

#import <MJRefresh/MJRefresh.h>
#import "KFDMarketInfoContainer.h"
#import "JTOptionBar.h"
#import "ui_config.h"
#import "KFDMarketNewsAliveTableViewCell.h"
#import "KFDMarketTradingStrategyTableViewCell.h"
#import "KFDMarketFinancialDatumTableViewCell.h"
#import "KFDMarketHolidayForecastTableViewCell.h"
#import "KFDMarketFinancialEventTableViewCell.h"
#import "KFDLiveNewsPiece.h"
#import "KFDTradingStrategy.h"
#import "KFDMarketInfoContainerModel.h"
#import "KFDAccountManager.h"
#import "KFDLoginViewController.h"
#import "KFDRegisterViewController.h"
#import "KFDMarketFinanceCalendarTableViewHeader.h"
#import "KFDMarketViewController.h"
#import "JRTXDiagramView.h"
#import "JTToast.h"
#import "KFDTradingStrategyViewController.h"
#import "UIAlertController+KFD.h"
#import "KFDDateCard.h"
#import "NSDate+range.h"
#import "NSDate+format.h"
//#import "KFDMarketFinancialDataMoreCell.h"
#import "KFDMarketFinancialEventTableViewCell.h"
#import <SDWebImage/SDImageCache.h>
#import <SDWebImage/SDWebImageManager.h>

#define KFDMarketNewsAliveTableViewTag 0
#define KFDMarketTradingStrategyTableViewTag 1
#define KFDMarketFinanceCalendarTableViewTag 2

#define KFDMarketNewsAliveTableViewCellReuseIdentifier @"KFDMarketNewsAliveTableViewCell"
#define KFDMarketNewsAliveTableViewCellNibName @"KFDMarketNewsAliveTableViewCell"

#define KFDMarketTradingStrategyTableViewCellReuseIdentifier @"KFDMarketTradingStrategyTableViewCell"
#define KFDMarketTradingStrategyTableViewCellNibName @"KFDMarketTradingStrategyTableViewCell"

#define KFDMarketFinancialDatumTableViewCellReuseIdentifier @"KFDMarketFinancialDatumTableViewCell"
#define KFDMarketFinancialDatumTableViewCellNibName @"KFDMarketFinancialDatumTableViewCell"

#define KFDMarketFinancialDataMoreCellReuseIdentifier @"KFDMarketFinancialDataMoreCell"
#define KFDMarketFinancialDataMoreCellNibName @"KFDMarketFinancialDataMoreCell"

#define KFDMarketHolidayForecastTableViewCellReuseIdentifier @"KFDMarketHolidayForecastTableViewCell"
#define KFDMarketHolidayForecastTableViewCellNibName @"KFDMarketHolidayForecastTableViewCell"

#define KFDMarketFinancialEventTableViewCellReuseIdentifier @"KFDMarketFinancialEventTableViewCell"
//#define KFDMarketFinancialEventTableViewCellNibName @"KFDMarketFinancialEventTableViewCell"


@interface KFDMarketInfoContainer ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,readonly) CGFloat width;

@property (nonatomic,readonly) CGRect diagramViewFrame;
@property (nonatomic,readonly) CGRect tableViewFrameLow;
@property (nonatomic,readonly) CGRect tableViewFrameHigh;

@property (weak,nonatomic) UIViewController* viewController;

@property (strong,nonatomic) KFDMarketInfoContainerModel* viewModel;

@property (strong,nonatomic) JTOptionBar* optionBar;
@property (strong,nonatomic) UITableView* newsAliveTableView;
@property (strong,nonatomic) UITableView* tradingStrategyTableView;
@property (strong,nonatomic) UITableView* financeCalendarTableView;
@property (assign,nonatomic) NSUInteger financialDataSectionRowCount;
@property (strong,nonatomic) NSDate* dateForFinancialData;
@property (strong,nonatomic) UIScrollView* calendar;

@end

@implementation KFDMarketInfoContainer
{
    NSInteger _tradingStrategyTableViewExpandedCellRow;
}

-(instancetype)initWithTableViewFrameLow:(CGRect)frameLow tableViewFrameHigh:(CGRect)frameHigh diagramViewFrame:(CGRect)diagramViewFrame viewController:(UIViewController *)viewController
{
    if (self=[super initWithFrame:frameLow]) {
        _width=self.bounds.size.width;
        _tableViewFrameLow=frameLow;
        _tableViewFrameHigh=frameHigh;
        _diagramViewFrame=diagramViewFrame;
        self.viewController=viewController;
        self.viewModel=[[KFDMarketInfoContainerModel alloc] init];
        self.backgroundColor=[UIColor whiteColor];
        [self setupOptionBar];
        [self setupCalendar];
        [self setupTableViews];
        [self addObserver];
        [self.viewModel registerObserver:self];
        [self.viewModel loadAliveNewsWithMaxCount:20 page:1];
        [self.viewModel loadTradingStrategiesWithMaxCount:20 page:1];
        [self.viewModel loadFinancialInfoWithDate:[NSDate date]];
        self.newsLiveTableViewCellHeights=[[NSMutableDictionary alloc] init];
        _tradingStrategyTableViewExpandedCellRow=-1;
    }
    return self;
}

-(void)addObserver
{
    NSNotificationCenter* notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(updateNewsAliveTableViewWithNotification:) name:KFDMarketNewsAliveTableViewDataSourceReadyNotification object:nil];
    [notificationCenter addObserver:self selector:@selector(updateTradingStrategyTableViewWithNotification:) name:KFDMarketTradingStrategyTableViewDataSourceReadyNotification object:nil];
    [notificationCenter addObserver:self selector:@selector(updateFinanceCalendarTableView) name:KFDMarketFinanceCalendarTableViewDataSourceReadyNotification object:nil];
}

-(void)setupOptionBar
{
    __weak typeof(self) weakSelf=self;
    CGFloat height=45;
    self.optionBar=[[JTOptionBar alloc] initWithFrame:CGRectMake(0, 0, self.width, height)];
    JTOptionBarConfiguration* config=[JTOptionBarConfiguration config];
    config.indicatorImage=[UIImage imageNamed:@"arrowstyle-up-reg.png"];
    self.optionBar.config=config;
    [self.optionBar addOptionWithValue:nil title:@"快讯直播" action:^(JTOptionBar *optionBar) {
        [weakSelf.tradingStrategyTableView removeFromSuperview];
        [weakSelf.financeCalendarTableView removeFromSuperview];
        [weakSelf addSubview:weakSelf.newsAliveTableView];
    }];
    [self.optionBar addOptionWithValue:nil title:@"交易策略" action:^(JTOptionBar *optionBar) {
        [weakSelf.newsAliveTableView removeFromSuperview];
        [weakSelf.financeCalendarTableView removeFromSuperview];
        [weakSelf addSubview:weakSelf.tradingStrategyTableView];
    }];
    [self.optionBar addOptionWithValue:nil title:@"财经日历" action:^(JTOptionBar *optionBar) {
        [weakSelf.newsAliveTableView removeFromSuperview];
        [weakSelf.tradingStrategyTableView removeFromSuperview];
        [weakSelf addSubview:weakSelf.financeCalendarTableView];
    }];
    [self addSubview:self.optionBar];
}

-(void)setupCalendar
{
    self.calendar=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 90/2, SCREEN_WIDTH, 70/2)];
    self.calendar.backgroundColor=KFD_WHITE;
    self.calendar.showsHorizontalScrollIndicator=NO;
    self.calendar.showsVerticalScrollIndicator=NO;
    self.calendar.pagingEnabled=YES;
    [self addSubview:self.calendar];
    [self.viewModel loadFinancialCalendardDates];
}

-(void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary *)change context:(nullable void *)context
{
    if ([keyPath isEqualToString:@"weekdays"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.calendar.contentSize=CGSizeMake(SCREEN_WIDTH*self.viewModel.weekdays.count/7, 0);
            NSMutableArray* dateCards=[NSMutableArray array];
            for (int i=0; i<self.viewModel.weekdays.count; i++) {
                KFDDateCard* dateCard=[[NSBundle mainBundle] loadNibNamed:@"KFDDateCard" owner:nil options:nil].firstObject;
                [dateCards addObject:dateCard];
                NSDate* date=self.viewModel.weekdays[i];
                dateCard.date=date;
                dateCard.selected=date.isWithinToday?YES:NO;
                dateCard.action=^{
                    self.dateForFinancialData=date;
                    for (int j=0; j<self.viewModel.weekdays.count; j++) {
                        if (i!=j) {
                            KFDDateCard* dateCard=dateCards[j];
                            dateCard.selected=NO;
                        }
                    }
                    [self.viewModel loadFinancialInfoWithDate:date];
                };
                dateCard.frame=CGRectMake(SCREEN_WIDTH*i/7, 0, SCREEN_WIDTH/7, 70/2);
                [self.calendar addSubview:dateCard];
            }
        });
    }
}

-(void)setupTableViews
{
    [self setupNewsAliveTableView];
    [self setupTradingStrategyTableView];
    [self setupFinanceCalendarTableView];
    [self addSubview:self.newsAliveTableView];
}
-(void)setupNewsAliveTableView
{
    self.newsAliveTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 90*0.5, self.width, self.bounds.size.height-90*0.5)];
    self.newsAliveTableView.tag=KFDMarketNewsAliveTableViewTag;
//    self.newsAliveTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.newsAliveTableView.separatorInset=UIEdgeInsetsMake(0, 75, 0, 10);
    self.newsAliveTableView.dataSource=self;
    self.newsAliveTableView.delegate=self;
    self.newsAliveTableView.allowsSelection=NO;
    UIView* header=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 40)];
    header.backgroundColor=[UIColor whiteColor];
    UIImageView* clockImgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    clockImgView.center=CGPointMake(63, 20);
    clockImgView.image=[UIImage imageNamed:@"time-ico"];
    [header addSubview:clockImgView];
    self.newsAliveTableView.tableHeaderView=header;
    __weak typeof(self) weakSelf=self;
    [self.newsAliveTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.viewModel loadAliveNewsWithMaxCount:weakSelf.viewModel.aliveNews.count page:1];
    }];
    [self.newsAliveTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.viewModel loadAliveNewsWithMaxCount:weakSelf.viewModel.aliveNews.count+20 page:1];
    }];
}
-(void)setupTradingStrategyTableView
{
    self.tradingStrategyTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 90*0.5, self.width, self.bounds.size.height-90*0.5)];
    self.tradingStrategyTableView.tag=KFDMarketTradingStrategyTableViewTag;
    self.tradingStrategyTableView.dataSource=self;
    self.tradingStrategyTableView.delegate=self;
    self.tradingStrategyTableView.allowsSelection=NO;
    __weak typeof(self) weakSelf=self;
    [self.tradingStrategyTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.viewModel loadTradingStrategiesWithMaxCount:weakSelf.viewModel.tradingStrategies.count page:1];
    }];
    [self.tradingStrategyTableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf.viewModel loadTradingStrategiesWithMaxCount:self.viewModel.tradingStrategies.count+20 page:1];
    }];
}
-(void)setupFinanceCalendarTableView
{
    self.financeCalendarTableView=[[UITableView alloc] initWithFrame:CGRectMake(0, (90+70)*0.5, self.width, self.bounds.size.height-90*0.5)];
//    self.financeCalendarTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.financeCalendarTableView.tag=KFDMarketFinanceCalendarTableViewTag;
    self.financeCalendarTableView.dataSource=self;
    self.financeCalendarTableView.delegate=self;
    self.financeCalendarTableView.allowsSelection=NO;
    self.financialDataSectionRowCount=0;
    __weak typeof(self) weakSelf=self;
    [self.financeCalendarTableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf.viewModel loadFinancialInfoWithDate:weakSelf.dateForFinancialData];
    }];
}

-(void)updateNewsAliveTableViewWithNotification:(NSNotification*)notificaiton
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.newsAliveTableView reloadData];
        if (self.newsAliveTableView.header.isRefreshing) {
            [self.newsAliveTableView.header endRefreshing];
        }
        if (self.newsAliveTableView.footer.isRefreshing) {
            [self.newsAliveTableView.footer endRefreshing];
            NSNumber* inc=notificaiton.userInfo[@"countIncrement"];
            if (inc.integerValue==0) {
                JTToast* toast=[JTToast makeText:@"没有更多了"];
                [toast showInView:self size:CGSizeMake(100, 40)];
            }
        }
    });
}
-(void)updateTradingStrategyTableViewWithNotification:(NSNotification*)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tradingStrategyTableView reloadData];
        if (self.tradingStrategyTableView.header.isRefreshing) {
            [self.tradingStrategyTableView.header endRefreshing];
        }
        if (self.tradingStrategyTableView.footer.isRefreshing) {
            [self.tradingStrategyTableView.footer endRefreshing];
            NSNumber* inc=notification.userInfo[@"countIncrement"];
            if (inc.integerValue==0) {
                JTToast* toast=[JTToast makeText:@"没有更多了"];
                [toast showInView:self size:CGSizeMake(100, 40)];
            }
        }
    });
}
-(void)updateFinanceCalendarTableView
{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.financialDataSectionRowCount=4;
        [self.financeCalendarTableView reloadData];
        if (self.financeCalendarTableView.header.isRefreshing) {
            [self.financeCalendarTableView.header endRefreshing];
        }
        if (self.financeCalendarTableView.footer.isRefreshing) {
            [self.financeCalendarTableView.footer endRefreshing];
        }
    });
}

#pragma mark - Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag==KFDMarketFinanceCalendarTableViewTag) {
        return 3;
    }
    return 1;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView.tag==KFDMarketFinanceCalendarTableViewTag) {
        switch (section) {
            case 0:
                return @"假期数据";
            case 1:
                return @"财经预告";
            case 2:
                return @"财经事件";
        }
    }
    return @"";
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView.tag==KFDMarketFinanceCalendarTableViewTag) {
        return 30;
    }
    return 0;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView.tag==KFDMarketFinanceCalendarTableViewTag) {
        KFDMarketFinanceCalendarTableViewHeader* header=[[KFDMarketFinanceCalendarTableViewHeader alloc] initWithFrame:CGRectMake(0, 0, self.width, 30)];
        UILabel* titleLabel=[[UILabel alloc] initWithFrame:header.bounds];
        titleLabel.textColor=KFD_TEXT_DARK_GRAY;
        titleLabel.textAlignment=NSTextAlignmentCenter;
        [header addSubview:titleLabel];
        switch (section) {
            case 0:
                titleLabel.text=@"财经数据";
                break;
            case 1:
                titleLabel.text=@"假期预告";
                break;
            case 2:
                titleLabel.text=@"财经事件";
                break;
            default:
                break;
        }
        return header;
    }else{
        return [UIView new];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger tag=tableView.tag;
    if (tag==KFDMarketNewsAliveTableViewTag) {
        return self.viewModel.aliveNews.count;
    }else if(tag==KFDMarketTradingStrategyTableViewTag){
        return self.viewModel.tradingStrategies.count;
    }else if(tag==KFDMarketFinanceCalendarTableViewTag){
        switch (section) {
            case 0:
                return self.viewModel.financialData.count;
//                return MIN(self.viewModel.financialData.count, self.financialDataSectionRowCount);
            case 1:
                return self.viewModel.holidayForecasts.count;
            case 2:
                return self.viewModel.financialEvents.count;
            default:
                return 0;
        }
    }else{
        return 0;
    }
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger tag=tableView.tag;
    if (tag==KFDMarketNewsAliveTableViewTag) {
        KFDMarketNewsAliveTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketNewsAliveTableViewCellReuseIdentifier];
        if (!cell) {
            NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketNewsAliveTableViewCellNibName owner:nil options:nil];
            cell = objects[0];
        }
        cell.marketInfoContainer=self;
        cell.tableView=tableView;
        cell.indexPath=indexPath;
        [cell setNewsPiece:self.viewModel.aliveNews[indexPath.row]];
        return cell;
    }else if(tag==KFDMarketTradingStrategyTableViewTag){
        KFDMarketTradingStrategyTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketTradingStrategyTableViewCellReuseIdentifier];
        if (!cell) {
            NSArray* objects=[[NSBundle mainBundle] loadNibNamed:KFDMarketTradingStrategyTableViewCellNibName owner:nil options:nil];
            cell=objects[0];
        }
        KFDTradingStrategy* tradingStrategy=self.viewModel.tradingStrategies[indexPath.row];
        [cell setTradingStrategy:tradingStrategy detailed:_tradingStrategyTableViewExpandedCellRow==indexPath.row?YES:NO];
        if (indexPath.row==_tradingStrategyTableViewExpandedCellRow) {
            [cell.expandButton setTitle:@"收起" forState:UIControlStateNormal];
            cell.contentLabel.numberOfLines=0;
            [cell setShowDetailsAction:^{
                _tradingStrategyTableViewExpandedCellRow=-1;
                [self.tradingStrategyTableView reloadData];
            }];
        }else{
            [cell.expandButton setTitle:@"查看全文" forState:UIControlStateNormal];
            cell.contentLabel.numberOfLines=2;
            [cell setShowDetailsAction:^{
                KFDAccountManager* accountManager=[KFDAccountManager sharedManager];
                if (accountManager.isLogin) {
                    _tradingStrategyTableViewExpandedCellRow=indexPath.row;
                    [self.tradingStrategyTableView reloadData];
                }else{
                    [UIAlertController presentLoginRegisterAlertControllerWithMessage:@"免费获取每日精品交易策略，市场变化轻松掌握10秒完成注册" byViewController:self.viewController];
                }
            }];
        }
        
        return cell;
    }else if(tag==KFDMarketFinanceCalendarTableViewTag){
        switch (indexPath.section) {
            case 0:
            {
                KFDMarketFinancialDatumTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketFinancialDatumTableViewCellReuseIdentifier];
                if (!cell) {
                    NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketFinancialDatumTableViewCellNibName owner:nil options:nil];
                    cell = objects[0];
                }
                cell.separatorInset=UIEdgeInsetsMake(0, 70, 0, 0);
                [cell setFinancialDatum:self.viewModel.financialData[indexPath.row]];
                return cell;
//                if (indexPath.row!=self.financialDataSectionRowCount-1) {
//                    KFDMarketFinancialDatumTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketFinancialDatumTableViewCellReuseIdentifier];
//                    if (!cell) {
//                        NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketFinancialDatumTableViewCellNibName owner:nil options:nil];
//                        cell = objects[0];
//                    }
//                    cell.separatorInset=UIEdgeInsetsMake(0, 70, 0, 0);
//                    [cell setFinancialDatum:self.viewModel.financialData[indexPath.row]];
//                    return cell;
//                }else{
//                    KFDMarketFinancialDataMoreCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketFinancialDataMoreCellReuseIdentifier];
//                    if (!cell) {
//                        cell=[[NSBundle mainBundle] loadNibNamed:KFDMarketFinancialDataMoreCellNibName owner:nil options:nil].firstObject;
//                    }
//                    __weak typeof(self) weakSelf=self;
//                    cell.loadMoreAction=^{
//                        weakSelf.financialDataSectionRowCount+=3;
//                        if (weakSelf.financialDataSectionRowCount>weakSelf.viewModel.financialData.count+1) {
//                            weakSelf.financialDataSectionRowCount=weakSelf.viewModel.financialData.count+1;
//                        }
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [weakSelf.financeCalendarTableView reloadData];
//                        });
//                    };
//                    return cell;
//                }
            }
            case 1:
            {
                KFDMarketHolidayForecastTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketHolidayForecastTableViewCellReuseIdentifier];
                if (!cell) {
                    NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketHolidayForecastTableViewCellNibName owner:nil options:nil];
                    cell = objects[0];
                }
                cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, SCREEN_WIDTH);
                [cell setHolidayForecast:self.viewModel.holidayForecasts[indexPath.row]];
                return cell;
            }
            case 2:
            {
                KFDMarketFinancialEventTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketFinancialEventTableViewCellReuseIdentifier];
                if (!cell) {
//                    NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketFinancialEventTableViewCellNibName owner:nil options:nil];
//                    cell = objects[0];
                    cell=[[KFDMarketFinancialEventTableViewCell alloc] init];
                }
                cell.separatorInset=UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, SCREEN_WIDTH);
                cell.financialEvent=self.viewModel.financialEvents[indexPath.row];
                [cell layout];
                [cell attach];
                return cell;
            }
            default:
            {
                return [UITableViewCell new];
            }
        }
    }else{
        return [UITableViewCell new];
    }
}

-(void)dealloc
{
    NSNotificationCenter* notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:KFDMarketNewsAliveTableViewDataSourceReadyNotification object:nil];
    [notificationCenter removeObserver:self name:KFDMarketTradingStrategyTableViewDataSourceReadyNotification object:nil];
    [notificationCenter removeObserver:self name:KFDMarketFinanceCalendarTableViewDataSourceReadyNotification object:nil];
}

#pragma mark - Table view delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (tableView.tag) {
        case KFDMarketNewsAliveTableViewTag:
        {
            NSNumber* height=self.newsLiveTableViewCellHeights[[NSString stringWithFormat:@"%ld",(long)indexPath.row]];
            if (height) {
                return height.floatValue;
            }
            
            KFDLiveNewsPiece* piece=self.viewModel.aliveNews[indexPath.row];
            
            if (piece.picture&&piece.picture.length>0) {
                SDWebImageManager* webImageManager=[SDWebImageManager sharedManager];
                NSURL* url=[NSURL URLWithString:piece.picture];
                UIImage* image=[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[webImageManager cacheKeyForURL:url]];
                if(image) {
                    NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketNewsAliveTableViewCellNibName owner:nil options:nil];
                    KFDMarketNewsAliveTableViewCell* cell = objects[0];
                    cell.tableView=tableView;
                    cell.indexPath=indexPath;
                    [cell setNewsPiece:self.viewModel.aliveNews[indexPath.row]];
                    return cell.height;
                }else{
                    [webImageManager downloadImageWithURL:[NSURL URLWithString:piece.picture] options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                        if (!error) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                            });
                        }
                    }];
                }
            }else{
                NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketNewsAliveTableViewCellNibName owner:nil options:nil];
                KFDMarketNewsAliveTableViewCell* cell = objects[0];
                cell.tableView=tableView;
                cell.indexPath=indexPath;
                [cell setNewsPiece:self.viewModel.aliveNews[indexPath.row]];
                return cell.height;
            }
        }
        case KFDMarketTradingStrategyTableViewTag:
        {
            if (indexPath.row==_tradingStrategyTableViewExpandedCellRow) {
                KFDTradingStrategy* strategy=self.viewModel.tradingStrategies[indexPath.row];
                NSDictionary* attributes=@{NSFontAttributeName:[UIFont systemFontOfSize:12]};
                CGRect boundingRect=[strategy.fullContent boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-42, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
                return 84.5+boundingRect.size.height;
            }else{
                return 113;
            }
        }
        case KFDMarketFinanceCalendarTableViewTag:
        {
            switch (indexPath.section) {
                case 0:
                    return 68;
                case 1:
                    return 60;
                case 2:
                {
                    KFDMarketFinancialEventTableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:KFDMarketFinancialEventTableViewCellReuseIdentifier];
                    if (!cell) {
//                        NSArray *objects = [[NSBundle mainBundle] loadNibNamed:KFDMarketFinancialEventTableViewCellNibName owner:nil options:nil];
//                        cell = objects[0];
                        cell=[[KFDMarketFinancialEventTableViewCell alloc] init];
                    }
                    cell.financialEvent=self.viewModel.financialEvents[indexPath.row];
                    [cell layout];
                    return cell.height;
                }
            }
        }
        default:
            return 40;
    }
}

-(void)scrollViewDidScroll:(nonnull UIScrollView *)scrollView
{
    float duration=0.4;
    CGPoint offset = scrollView.contentOffset;
    if (offset.y<-100) {
        if ([self.viewController isKindOfClass:[KFDMarketViewController class]]) {
            [UIView animateWithDuration:duration animations:^{
                ((KFDMarketViewController*)self.viewController).diagramView.alpha=1;
            }];
        }
        [UIView animateWithDuration:duration animations:^{
            self.frame=self.tableViewFrameLow;
            CGRect frame=CGRectMake(0, 90*0.5, self.width, self.bounds.size.height-90*0.5);
            self.newsAliveTableView.frame=frame;
            self.tradingStrategyTableView.frame=frame;
            self.financeCalendarTableView.frame=CGRectMake(0, (90+70)/2, self.width, self.bounds.size.height-(90+70)*0.5);
        }];
    }else if (offset.y>100){
        if ([self.viewController isKindOfClass:[KFDMarketViewController class]]) {
            [UIView animateWithDuration:duration animations:^{
                ((KFDMarketViewController*)self.viewController).diagramView.alpha=0;
            }];
        }
        [UIView animateWithDuration:duration animations:^{
            self.frame=self.tableViewFrameHigh;
            CGRect frame=CGRectMake(0, 90*0.5, self.width, self.bounds.size.height-90*0.5);
            self.newsAliveTableView.frame=frame;
            self.tradingStrategyTableView.frame=frame;
            self.financeCalendarTableView.frame=CGRectMake(0, (90+70)/2, self.width, self.bounds.size.height-(90+70)*0.5);
        }];
    }
}

@end
